package com.heima.wemedia.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.model.common.constants.message.NewsAutoScanConstants;
import com.heima.model.common.constants.message.NewsUpOrDownConstants;
import com.heima.model.common.constants.message.PublishArticleConstants;
import com.heima.model.common.constants.wemedia.WemediaConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.NewsAuthDTO;
import com.heima.model.wemedia.dtos.WmNewsDTO;
import com.heima.model.wemedia.dtos.WmNewsPageReqDTO;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vo.WmNewsVO;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


@Service
@Slf4j
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {


    // 图片前缀

    @Value("${file.oss.web-site}")
    private String webSite;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 自媒体文章查询
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmNewsPageReqDTO dto) {
        if (dto == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        dto.checkParam();

        LambdaQueryWrapper<WmNews> wrapper = Wrappers.lambdaQuery();
        // 根据所属频道id查询
        if (dto.getChannelId() != null) {
            wrapper.eq(WmNews::getChannelId, dto.getChannelId());
        }

        // 根据状态查询
        if (dto.getStatus() != null) {
            wrapper.eq(WmNews::getStatus, dto.getStatus());
        }

        // 书否输入关键字
        if (StringUtils.isNotBlank(dto.getKeyword())) {
            wrapper.like(WmNews::getContent, dto.getKeyword());
        }
        // 是否选择时间
        wrapper.between(dto.getBeginPubDate() != null && dto.getEndPubDate() != null, WmNews::getCreatedTime, dto.getBeginPubDate(), dto.getEndPubDate());


        wrapper.orderByDesc(WmNews::getCreatedTime);
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 分页
        Page<WmNews> page = new Page<>(dto.getPage(), dto.getSize());
        IPage<WmNews> iPage = this.page(page, wrapper);

        PageResponseResult result = new PageResponseResult(dto.getPage(),
                dto.getSize(), iPage.getTotal(),
                iPage.getRecords());
        // 设置图片访问前缀
        result.setHost(webSite);
        return result;
    }


    /**
     * 自媒体文章发布
     *
     * @param dto
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult submitNews(WmNewsDTO dto) {
        // 1 将dto转化为wmnews对象
        if (StringUtils.isBlank(dto.getContent())) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 1.1 校验参数(content 登录)
        WmNews wmNews = new WmNews();
        //1.2 将将dto参数里面的值设置到wmNews
        BeanUtils.copyProperties(dto, wmNews);
        wmNews.setCreatedTime(new Date());
        // 用户校验
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 1.3 如果type等于-1,暂时设置type为null
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())) {
            // 字段不能穿负数 , dto不能为null,后边自动会改
            wmNews.setType(null);
        }

        // 1.4 封面dto传入的是list<string> 图片集合 转化为字符串用逗号拼接
        if (CollectionUtils.isNotEmpty(dto.getImages())) {
            // 创建流过滤 图片路径
            String imagesStr = imagesToStr(dto.getImages());
            wmNews.setImages(imagesStr);
        }
        // 设置id
        wmNews.setUserId(user.getId());
        saveOrUpdate(wmNews);
        // 2 保存或修改wmNews对象
        saveOrUpdateWmNews(wmNews);
        if (WemediaConstants.WM_NEWS_DRAFT_STATUS.equals(dto.getStatus())) {
            return ResponseResult.okResult();
        }

        // 3 保存 文章内容或封面和 素材关联关系
        // 抽取内容中所有素材url路径集合
        // 转化
        List<Map> contentMap = JSON.parseArray(dto.getContent(), Map.class);
        List<String> contentUrls = parseContentImages(contentMap);

        // 保存文章内容和 素材的关联关系
        if (CollectionUtils.isNotEmpty(contentUrls)) {
            saveRelativeInfo(contentUrls, wmNews.getId(), WemediaConstants.WM_CONTENT_REFERENCE);
        }
        // 保存文章的封面和关系
        saveRelativeInfoForCover(contentUrls, wmNews, dto);


        // 发送自动审核到mq
        rabbitTemplate.convertAndSend(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_QUEUE, wmNews.getId());
        log.info("以自动发送 文章自动审核 消息内容" + wmNews.getId());
        return ResponseResult.okResult();
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult findWmNewsById(Integer id) {
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = this.getById(id);
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        ResponseResult result = ResponseResult.okResult(wmNews);
        result.setHost(webSite);
        return result;
    }

    /**
     * 删除文章根据id
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult delNews(Integer id) {
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "文章Id不可缺少");
        }
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        // 判断当前文章的状态 status==9  enable == 1
        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())
                && wmNews.getEnable().equals(WemediaConstants.WM_NEWS_UP)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章已发布，不能删除");
        }

        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery()
                .eq(WmNewsMaterial::getNewsId, wmNews.getId()));
        //5.删除文章
        removeById(wmNews.getId());
        return ResponseResult.okResult();
    }

    /**
     * 上架、下架
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDTO dto) {
        // 检查参数
        if (dto == null && dto.getId() == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        Short enable = dto.getEnable();
        if (enable == null ||
                !WemediaConstants.WM_NEWS_UP.equals(enable) && !WemediaConstants.WM_NEWS_DOWN.equals(enable)) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "上下架状态错误");
        }
        WmNews wmNews = this.getById(dto.getId());
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        // 判断文章是否发布
        if (!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "当前文章不是发布状态，不能上下架");
        }
        //4.修改文章状态，同步到app端（）
        update(Wrappers.<WmNews>lambdaUpdate()
                .eq(WmNews::getId, dto.getId())
                .set(WmNews::getEnable, dto.getEnable()));
        if (wmNews.getArticleId()!=null) {
            if(enable.equals(WemediaConstants.WM_NEWS_UP)){
                // 上架消息
                rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,
                        NewsUpOrDownConstants.NEWS_UP_ROUTE_KEY,wmNews.getArticleId());
            }else {
                // 下架消息
                rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,
                        NewsUpOrDownConstants.NEWS_DOWN_ROUTE_KEY,wmNews.getArticleId());
            }
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);


    }

    /**
     * 人工审核员分页查询文章列表
     */
    @Autowired
    WmNewsMapper wmNewsMapper;

    @Override
    public ResponseResult findList(NewsAuthDTO dto) {
        // 校验参数 分页数据
        dto.checkParam();
        Integer page = dto.getPage();
        dto.setPage(((page - 1) * dto.getSize()));
        // 执行条件分页查询
        List<WmNewsVO> listAndPage = wmNewsMapper.findListAndPage(dto);
        long count = wmNewsMapper.findListCount(dto);

        PageResponseResult result = new PageResponseResult(page, dto.getSize(), count, listAndPage);
        result.setHost(webSite);
        // 返回结果
        return result;
    }

    /**
     * 查询文章详情
     *
     * @param id
     * @return
     */
    // 注入作业查询

    @Autowired
    WmUserMapper wmUserMapper;

    @Override
    public ResponseResult findWmNewsVo(Integer id) {
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "id不能为null");
        }
        WmNews wmNews = this.getById(id);
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.查询作者
        WmUser wmUser = null;
        if (wmNews.getUserId() != null) {
            // 查询作者
            wmUser = wmUserMapper.selectById(wmNews.getUserId());
        }
        WmNewsVO wmNewsVO = new WmNewsVO();
        BeanUtils.copyProperties(wmNews, wmNewsVO);
        if (wmUser != null) {
            wmNewsVO.setAuthorName(wmUser.getName());
        }
        // 设置前缀
        ResponseResult.okResult(wmNewsVO).setHost(webSite);
        return ResponseResult.okResult(wmNewsVO);
    }

    /**
     * 自媒体文章人工审核
     * @param status  2  审核失败  4 审核成功
     * @param dto
     * @return
     */
    @Override
    public ResponseResult updateStatus(Short status, NewsAuthDTO dto) {
        if (dto==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //2.查询文章
        WmNews wmNews = getById(dto.getId());
        // 检查文章状态 不能为9  已发布
        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"文章已发布");
        }
        //3.修改文章状态
        wmNews.setStatus(status);
        if(StringUtils.isNotBlank(dto.getMsg())){
            wmNews.setReason(dto.getMsg());
        }
        updateById(wmNews);
        //4. 通知定时发布文章
        long publicTime = wmNews.getPublishTime().getTime();
        long nowTime = new Date().getTime();
        long remainTime=publicTime-nowTime;

        rabbitTemplate.convertAndSend(PublishArticleConstants.DELAY_DIRECT_EXCHANGE,
                PublishArticleConstants.PUBLISH_ARTICLE_ROUTE_KEY,
                wmNews.getId(),
                (message -> {
                    message.getMessageProperties().setHeader("x-delay",remainTime<=0?0:remainTime);
                    return message;
                }));
        log.info("立即发布文章通知成功发送，文章id : {}", wmNews.getId());

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    /**
     * 保存文章的封面和关系
     *
     * @param contentUrls
     * @param wmNews
     */
    private void saveRelativeInfoForCover(List<String> contentUrls, WmNews wmNews, WmNewsDTO dto) {
        // 前端传入的封面集合 (有前缀)
        List<String> images = dto.getImages();
        // 判断特殊 dto type 是否等于-1 ,需要生成封面
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())) {
            // 自动生成封面
            // 无图
            if (CollectionUtils.isEmpty(contentUrls)) {
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            } else if (contentUrls.size() > 0 && contentUrls.size() <= 2) {
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                images = contentUrls.stream().limit(1).collect(Collectors.toList());
            } else {
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                images = contentUrls.stream().limit(3).collect(Collectors.toList());
            }
            if (CollectionUtils.isNotEmpty(images)) {
                // 转化为字符串
                wmNews.setImages(imagesToStr(images));
            }

            // 修改wmNews
            updateById(wmNews);

        }
        if (CollectionUtils.isNotEmpty(images)) {
            images = images.stream().map(url -> url.replaceAll(webSite, "")).distinct()
                    .collect(Collectors.toList());// 保存封面和素材的关联关系
            saveRelativeInfo(images, wmNews.getId(), WemediaConstants.WM_IMAGE_REFERENCE);
        }


    }

    /**
     * [{type,text,value:xx}]
     * 过滤
     *
     * @param contentMap
     * @return
     */
    private List<String> parseContentImages(List<Map> contentMap) {
        return contentMap.stream()
                // 过滤type images的数据
                .filter(map -> WemediaConstants.WM_NEWS_TYPE_IMAGE.equals(map.get("type")))
                // 去除url的路径
                .map(m -> m.get("value").toString())
                // 去除前置路径
                .map(url -> url.replaceAll(webSite, ""))
                .distinct()
                // 转化为list流
                .collect(Collectors.toList());
    }


    /**
     * @param wmNews
     */
    private void saveOrUpdateWmNews(WmNews wmNews) {
        // 1 讲过wmNews对象信息不全
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        // 设置上下架 ,默认上架
        wmNews.setEnable(WemediaConstants.WM_NEWS_UP);
        // 2 判断是否携带id
        if (wmNews.getId() == null) {
            // 2.1 如果没id 就保存
            save(wmNews);
        } else {
            // 2.2 如果有id 就修改(先删除关联关系,在修改)
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery()
                    .eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            this.updateById(wmNews);
        }


    }

    /**
     * webSite去掉和逗号拼接到一起
     *
     * @param images
     * @return
     */
    private String imagesToStr(List<String> images) {
        return images.stream()
                // 去除前置路线
                .map(url -> url.replaceAll(webSite, ""))
                // 去重
                .distinct()
                // 使用逗号拼接
                .collect(Collectors.joining(","));

    }

    @Autowired
    WmMaterialMapper wmMaterialMapper;

    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;

    /**
     * 保存素材 文章的关联关系
     *
     * @param materialUrls 素材路径合集
     * @param newsId
     * @param type
     */
    private void saveRelativeInfo(List<String> materialUrls, Integer newsId, short type) {
        // 1 根据图片路劲列表 及 登录用户id 查询相关素材id
        Integer userId = WmThreadLocalUtils.getUser().getId();
        List<Integer> ids = wmMaterialMapper.selectRelationsIds(materialUrls, userId);
        // 2 检查id的数量 是否小于url集合的size,如果小于代表素材缺失,抛异常
        if (ids.size() < materialUrls.size()) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "引用参数已经失效");
        }
        // 3 批量保存关联关系 使用foreach批量插入
        wmNewsMaterialMapper.saveRelations(ids, newsId, type);
    }
}
